package com.crm.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.crm.entity.Modules;
import com.crm.entity.Users;
import com.crm.service.ModulesService;
import com.crm.service.UsersService;
import com.crm.util.MD5Util;
import com.crm.util.Result;

//、登录验证的控制层、
@RestController
@RequestMapping("/public")
public class LoginController {
	@Autowired
	private UsersService us;// 自动注入服务层

	@RequestMapping("/login")
	public JSONObject login(Users u, HttpSession session) {
		JSONObject jsonObject = new JSONObject();
		Users userForBase = us.getByUserName(u.getLoginName());
		Integer errorCount = 0;// 判断是否出错的登录次数
		UsernamePasswordToken t = null;
		if (userForBase == null) {
			jsonObject.put("success", false);
			jsonObject.put("message", "登录失败，用户不存在！");
			return jsonObject;
		} else {
			if (!MD5Util.verify(u.getPassword(), userForBase.getPassword())) {
				// 密码不对、修改密码错误次数+1
				// 修改密码错误次数的方法 us.getBypsdWrongTime()
				us.getBypsdWrongTime(userForBase.getId());
				jsonObject.put("success", false);
				String msg;
				if (errorCount == 5) {
					msg = "密码错误次数上限，账户已锁定！<br>请找回密码或联系管理员重置密码。";
				} else {
					msg = "密码错误！你还有" + (5 - errorCount - 1) + "次机会！";
				}
				jsonObject.put("message", msg);
				System.out.println(userForBase.getIsLockout());
				return jsonObject;
			} else if (userForBase.getIsLockout() == 1) {//0不锁定，1锁定
				jsonObject.put("success", false);
				jsonObject.put("message", "登录失败，账户已锁定！<br>请找回密码或联系管理员重置密码。");
				return jsonObject;
			} else {
				// 登录成功把错误密码次数改成0
				// 将密码错误次数清零的方法 us.getBypsdWrongTimeClear()
				us.getBypsdWrongTimeClear(userForBase.getId());
				try {
					Subject subject = SecurityUtils.getSubject();
					t = new UsernamePasswordToken(userForBase.getLoginName(), userForBase.getPassword());
					subject.login(t);
				} catch (AuthenticationException e) {
					// TODO: handle exception
					e.printStackTrace();
				} catch (AuthorizationException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}
		// 把数据放到session中
		session.setAttribute("userForBase_session", userForBase);
		// 登录成功 调用修改用户最后一次登录时间
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		Users uus = new Users();
		uus.setId(userForBase.getId());// 拿到id
		uus.setLastLoginTime(df.format(new Date()));// 去修改最后一次登录的时间
		us.updateLastLoginTime(uus);// 调用方法
		jsonObject.put("success", true);
		jsonObject.put("token", t);
		jsonObject.put("user", userForBase);
		return jsonObject;
	}

	/**
	 * 修改密码
	 * 
	 * @param users
	 * @return
	 */
	@RequestMapping("/updatePwd")
	public JSONObject updatePwd(Users users,String pwd,String name,int id) {
		JSONObject jsonObject = new JSONObject();
		Users userForBase = us.getByUserName(name);
		System.out.println("旧密码"+pwd);
		System.out.println("新密码"+users.getPassword());
		System.out.println("姓名"+name);
		if (!MD5Util.verify(pwd, userForBase.getPassword())) {
			jsonObject.put("succ", false);
			jsonObject.put("message", "原密码不对");
		} else {
			users.setPassword(MD5Util.getMD5(users.getPassword()));
			users.setId(id);
			// 调用修改密码的方法
			us.updatePwd(users);
			jsonObject.put("succ", true);
			jsonObject.put("message", "密码修改成功");
		}
		return jsonObject;
	}
}
